import { ResultUtil } from '../common/HandlerRespUtil';
import { Config } from '../sdk/ConfigManager';
import { LingmaSDKTool } from '../sdk/LingmaSDKTool';
import axios from 'axios';
import moment from 'moment';
import os from 'os';
import {
  AIResponse,
  HandlePolicy,
  RawRequest,
  RequestPostHandler,
} from '../sdk/RequestHandleSDK';

/**
 * 自定义脚本过滤器,通过该脚本可以完成将请求内容发送到远程服务器进行处理（如代码扫描、内容审计等）
 */
export const llmResultAuditHandler: RequestPostHandler = {
  handle: async (request: RawRequest, response: AIResponse, SDKTool: LingmaSDKTool) => {
    // 操作人名称
    const userName = SDKTool.user.name;
    // 操作人id
    const userId = SDKTool.user.uid;
    // ide
    const ide = SDKTool.idePlatform;
    // ide
    const { ideVersion } = SDKTool;
    // 操作时间
    const operationTime = moment().format('YYYY-MM-DD HH:mm:ss');
    // 操作ip
    const opeartionIp = getIpAddress();
    // 操作业务场景(补全 or 问答场景)
    const bizType = 'chat';
    // 操作的请求id
    const { requestId } = request;
    // 操作action
    const { action } = request;
    // 操作内容(此处建议参考自身审计需求选取合适字段，避免上报内容过大(超过16k)导致上报失败)
    const inferredResult = response.inferredResult.text;


    // 上报sls
    // sls的Project名称
    const slsProject = 'xxx';
    // sls的LogStore名称
    const slsLogStore = 'xxx';
    // sls实例所在地域的endPoint
    const endPoint = 'cn-hangzhou.log.aliyuncs.com';
    const slsWebTrackingUrl = `http://${slsProject}.${endPoint}/logstores/${slsLogStore}/track?APIVersion=0.6.0&request_id=${requestId}&action=${action}&biz_type=${bizType}&user_name=${userName}&user_id=${userId}&ide=${ide}&ide_version=${ideVersion}&operation_time=${operationTime}&opeartion_ip=${opeartionIp}&inferredResult=${inferredResult}`;
    axios.get(slsWebTrackingUrl).catch((error) => {
      console.error(error);
    });

    // 返回过滤结果
    return ResultUtil.buildPostHandlerResponse(HandlePolicy.NO_OPS, response.inferredResult, '无需处理');
  },
};

/**
 * 将自定义脚本过滤器添加到配置中
 * @param config LingmaExtensionSDK提供的统一管理配置的对象
 */
export function modifyConfig(config: Config) {
  config.postContentHandlers.push(llmResultAuditHandler);
  return config;
}

function getIpAddress() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];

    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (
        alias.family === 'IPv4' &&
        alias.address !== '127.0.0.1' &&
        !alias.internal
      ) return alias.address;
    }
  }

  return 'No IP address found';
}

